{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# socket\n",
    "\n",
    "## 服务端"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import socket\n",
    "import time\n",
    "import threading\n",
    "\n",
    "local_addr = ('0.0.0.0', 10015)\n",
    "buff_len = 1024\n",
    "\n",
    "\n",
    "def conn_proc(sock, addr):\n",
    "\n",
    "    print('accept new connection from %s:%s...' % addr)\n",
    "    # 发送数据给客户端\n",
    "    sock.send('welcome'.encode('utf-8'))\n",
    "\n",
    "    while True:\n",
    "\n",
    "        print('wating next message...')\n",
    "        # 阻塞接收客户端数据\n",
    "        date = sock.recv(buff_len)\n",
    "        if not date or date.decode('utf-8') == 'exit':\n",
    "            break\n",
    "        print(date.decode('utf-8'))\n",
    "        sock.send(('server ' + str(time.time())).encode('utf-8'))\n",
    "\n",
    "    sock.close()\n",
    "    print('close connection %s:%s' % addr)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    # 创建一个socket\n",
    "    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
    "    # 绑定监听的地址和端口\n",
    "    tcp.bind(local_addr)\n",
    "    # 开始监听端口，等待连接的最大数量为10\n",
    "    tcp.listen(10)\n",
    "\n",
    "    while True:\n",
    "        # 阻塞等待客户端过来的tcp连接\n",
    "        sock, addr = tcp.accept()\n",
    "        print(type(sock), type(addr))\n",
    "        # 创建一个新线程来处理TCP连接\n",
    "        threading.Thread(target=conn_proc, args=(sock, addr)).start()\n",
    "\n",
    "    # 关闭socket\n",
    "    tcp.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 客户端"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#!/usr/bin/env python\n",
    "#coding=utf-8\n",
    "\n",
    "import time\n",
    "import socket\n",
    "\n",
    "server_addr = ('127.0.0.1', 12345)\n",
    "buff_len = 1024\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    # 创建一个socket\n",
    "    tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
    "    # 建立连接\n",
    "    tcp.connect(server_addr)\n",
    "\n",
    "    # 发送数据给服务器\n",
    "    tcp.send('hello server.'.encode('utf-8'))\n",
    "    # 阻塞接收服务器数据\n",
    "    print(tcp.recv(buff_len).decode('utf-8'))\n",
    "\n",
    "    while True:\n",
    "        text = input(\">>\")\n",
    "        tcp.send(text.encode('utf-8'))\n",
    "        date = tcp.recv(buff_len)\n",
    "        if not date or date.decode('utf-8') == 'exit':\n",
    "            break\n",
    "        print(date.decode('utf-8'))\n",
    "\n",
    "    # 关闭socket\n",
    "    tcp.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# socketserver\n",
    "\n",
    "## 服务端"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import socketserver\n",
    "\n",
    "\n",
    "class MyHandler(socketserver.BaseRequestHandler):\n",
    "    def handle(self):\n",
    "        # 通信循环\n",
    "        while True:\n",
    "            # print(self.client_address)\n",
    "            # print(self.request) #self.request=conn\n",
    "            try:\n",
    "                data = self.request.recv(1024)\n",
    "                print('receive {}'.format(data.decode('utf-8')))\n",
    "                if len(data.strip()) == 0: break\n",
    "                self.request.send(data.upper())\n",
    "            except ConnectionResetError:\n",
    "                break\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    s = socketserver.ThreadingTCPServer(('127.0.0.1', 12345), MyHandler, bind_and_activate=True)\n",
    "    s.serve_forever()  # 代表连接循环\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import socketserver\n",
    "from datetime import datetime\n",
    "import threading\n",
    "import sys\n",
    "\n",
    "\n",
    "class MyHandler(socketserver.BaseRequestHandler):\n",
    "\n",
    "    def task_listen(self):\n",
    "        while True:\n",
    "            try:\n",
    "                data = self.request.recv(4096)\n",
    "            except OSError as e:\n",
    "                break\n",
    "            if data:\n",
    "                try:\n",
    "                    sys.stdout.write(data.decode())\n",
    "                except UnicodeDecodeError:\n",
    "                    sys.stdout.write(data)\n",
    "                sys.stdout.write('\\n')\n",
    "\n",
    "    def task_send(self):\n",
    "        while True:\n",
    "            try:\n",
    "                data = sys.stdin.readline()\n",
    "                print('输入：', data)\n",
    "                if data.strip():\n",
    "                    self.request.send(data.encode())\n",
    "                else:\n",
    "                    break\n",
    "            except ConnectionResetError:\n",
    "                break\n",
    "\n",
    "    def handle(self):\n",
    "        print('客户端已连接', self.client_address)\n",
    "        th1 = threading.Thread(target=self.task_listen, daemon=True)\n",
    "        th2 = threading.Thread(target=self.task_send, daemon=True)\n",
    "\n",
    "        th1.start()\n",
    "        th2.start()\n",
    "        th2.join()\n",
    "        print('程序结束')\n",
    "        self.server.shutdown()\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    import argparse\n",
    "\n",
    "    parser = argparse.ArgumentParser()\n",
    "    parser.add_argument('-p', '--port', type=int)\n",
    "    args = parser.parse_args()\n",
    "    if args.port:\n",
    "        s = socketserver.ThreadingTCPServer(('0.0.0.0', args.port), MyHandler, bind_and_activate=True)\n",
    "        s.serve_forever()  # 代表连接循环\n",
    "    else:\n",
    "        print(parser.format_help())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "165px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
